#include <mega8.h>
#define R_division 4
//   

const unsigned char codes[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
/*                              0    1    2    3    4    5    6    7    8    9    */
unsigned char data[4]={0x00,0x00,0x00,0x00};
unsigned char counter=0;

unsigned int getADC()
//   
{
 unsigned int v;
 //    
 ADCSRA=(1<<ADSC);
 //   
 while (ADCSRA.4==0);
 //   
 v=ADCW;
 return v;
}

interrupt [TIM0_OVF] Timer0_ovf(void)  
//    0   7-seg
{
 switch(counter)
               {
                case 0: PORTB=data[counter]; PORTD.3=1; break;
                case 1: PORTB=data[counter]; PORTD.2=1; break;
                case 2: PORTB=data[counter]; PORTD.1=1; break;
                case 3: PORTB=data[counter]; PORTD.0=1; break;
               } 
                counter++;
                if (counter>=4)
                             {
                              counter=0;
                             }
}

unsigned int convert_data()
//       
{
 unsigned int temp,res,voltage;    
 unsigned int u;
 voltage=R_division*2.56*u*1.024;
 //  
 
 temp=voltage;
 res=temp/1000;			//Calculate 1000-s
 data[3]=codes[res];
 temp=temp-res*1000;
 
 res=temp/100;			//Calculate 100-s
 data[2]=codes[res];
 temp=temp-res*100;
 
 res=temp/10;			//Calculaate 10-s
 data[1]=codes[res];
 temp=temp-res*10;
 
 data[0]=codes[temp];	//Calculate 1-s       
 return data[3];
}

void main(void)
//  
{
 unsigned int u;
 /*   */   
 DDRB=0xFF; //        ( )
 DDRD=0xFF; //       
 DDRC=0x00;  //       
 
 /*   */    
 ADCSRA=(1<<ADEN)|(1<<ADPS2)|(1<<ADPS0);
 //  ,    /32
 ADMUX=(0<<REFS1)|(0<<REFS0)|(0<<MUX0)|(0<<MUX1)|(0<<MUX2)|(0<<MUX3);
 //    2.56     AREF,     PC0
 
 /*   0 */
 TIMSK=(1<<TOIE0); 
 //   /0    
 TCCR0=(1<<CS00)|(1<<CS01)|(0<<CS02);                                 
 //    /64 
 TCNT0=0x00; 
 while(1)
 {
 u=getADC(); 
 //    
 data[3]=convert_data(); 
 }      
 #asm("sei"); 
 //   
}